package com.sigerap.insumo.service;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;

import com.sigerap.common.util.*;
import com.sigerap.insumo.model.DetalleSolicitud;
import com.sigerap.insumo.model.Insumo;
import com.sigerap.insumo.model.InsumoProveedor;
import com.sigerap.insumo.model.dao.InsumoDAO;
import com.sigerap.insumo.model.dao.jpa.JPAInsumoDAO;
import com.sigerap.proveedor.model.Proveedor;
/**
 * 
 * @author Spirit-20121
 *
 */
public class InsumoService {
	private EntityManager em;
	private InsumoDAO insumoDAO;

	public InsumoService() {
		em = Utilitario.getInstance().getEntityManager();
		insumoDAO = new JPAInsumoDAO(em);
	}

	public List<Insumo> listarInsumos() {
		// TODO Auto-generated method stub
		return insumoDAO.findAll();
	}

	public Insumo buscarInsumoByNombre(Insumo insumo) {
		// TODO Auto-generated method stub
		return insumoDAO.findByNombre(insumo);
	}

	public Insumo registrarInsumo(Insumo i) {
		Insumo newInsumo=null;		
		EntityTransaction tx= em.getTransaction();
		System.out.println("antes del try de service");
		try{
			tx.begin();
			newInsumo =insumoDAO.insert(i);
			System.out.println("inserto insumo");
			tx.commit();
			
		}catch(Exception ex){
			System.out.println("catch de service");
			tx.rollback();
			ex.printStackTrace();
			throw new RuntimeException("No se pudo eliminar");
		}
		return newInsumo;
	}

	public InsumoProveedor registrarInsumoProveedor(
			InsumoProveedor insumoProveedor) {
		// TODO Auto-generated method stub
		InsumoProveedor newInsumoProveedor=null;
		EntityTransaction tx=em.getTransaction();
		try{
			tx.begin();
			System.out.println("en tx");
			newInsumoProveedor =insumoDAO.insertInsPro(insumoProveedor);
			System.out.println("inserto ip en service!!!!");
			tx.commit();
		}catch(Exception ex){
			tx.rollback();
			ex.printStackTrace();
			throw new RuntimeException("No se pudo eliminar");
		}
		return newInsumoProveedor;
	}

	public DetalleSolicitud registrarSolicitud(DetalleSolicitud detalleSolicitud) {
		// TODO Auto-generated method stub
		DetalleSolicitud ds= new DetalleSolicitud();
		EntityTransaction tx=em.getTransaction();
		try {
			tx.begin();
			ds=insumoDAO.insertSolicitud(detalleSolicitud);
			tx.commit();
		} catch (Exception ex) {
			// TODO Auto-generated catch block
			tx.rollback();
			ex.printStackTrace();
			throw new RuntimeException("No se pudo eliminar");
		}
		return ds;
	}

}
